﻿using System.Data.SqlClient;
using System;
using System.IO;
using Microsoft.DirectX.AudioVideoPlayback;
using System.Windows.Threading;
using System.Windows;
using System.Management;
using Microsoft.DirectX.DirectSound;
using System.Threading;

namespace SoundServant
{
    public partial class Recorder
    {

        public string SongLoadedTitle { get { return songLoadedTitle; } }
        public string SongLoadedScripture { get { return songLoadedScripture; } }
        public string SongTimeLeft { get { if (songState == SongStates.Loaded || songState == SongStates.Playing) return ("-" + (int)((songPlayer.Duration - songPlayer.CurrentPosition) / 60) + ":" + ((songPlayer.Duration - songPlayer.CurrentPosition) % 60).ToString("00")); else return "-0:00"; } }
        public string SongToLoad { set { songToLoad = value; songLoadTickTock = 0; } }
        public int SongLength { get { if (songPlayer != null) return (int)songPlayer.Duration; else return 0; } }
        public int SongPosition { get { if (songPlayer != null) return (int)songPlayer.CurrentPosition; else return 0; } }
        public SongStates SongState { get { return songState; } }

        public event VoidEventHandler SongLoaded;
        public event VoidEventHandler SongStarted;
        public event VoidEventHandler SongLastPlayed;
        public event VoidEventHandler SongUnloaded;
        public event VoidEventHandler SongStopped;
        public event VoidEventHandler SongLoading;

        private bool IsInt(string test)
        {
            try { int.Parse(test); return true; }
            catch { return false; }
        }

        void SongLoadTick(object sender, EventArgs e)
        {
            if (songLoadTickTock == 10) { songLoadTickTock = null; SongLoad(); }
            else if (songLoadTickTock != null) { songLoadTickTock++; }
        }

        public void SongLoad()
        {
            if (songState != SongStates.Playing && IsInt(songToLoad))
            {
                SongLoading();
                int number = int.Parse(songToLoad);
                SqlCommand dbCommand = new SqlCommand("SELECT songNumber, songTitle, songScripture, songFile FROM songs WHERE songBook = " + musicSongbook + " AND songNumber=" + number, dbConnection);
                SqlDataReader dbReader = dbCommand.ExecuteReader();
                if (dbReader.HasRows)
                {
                    dbReader.Read();
                    songLoaded = number;
                    songLoadedTitle = dbReader["songTitle"].ToString();
                    songLoadedScripture = dbReader["songScripture"].ToString();
                    string songFile = dbReader["songFile"].ToString();
                    try
                    {
                        songPlayer = new Audio(Options.Default.BaseDirectory + "\\" + Options.Default.SongDirectory + "\\" + musicSongbook + "\\" + songFile);
                        Logs.Information("Song Player", "Song loaded - Song Number: " + number + " Title: " + songLoadedTitle + " Scripture: " + songLoadedScripture);
                        songState = SongStates.Loaded;
                        SongLoaded();
                    }
                    catch (Exception e)
                    {
                        Logs.Error("Song Player", "Unable to load song. The file may be missing, corrupt or unaccessible - Error: ", e.ToString());
                    }
                }
                else
                {
                    songState = SongStates.Ready; SongUnloaded();
                }
                dbReader.Close();
            }
            else { songState = SongStates.Ready; SongUnloaded(); }
        }
        public void SongStartStop()
        {
            if (songState == SongStates.Loaded && songLoadTickTock == null)
            {
                songState = SongStates.Playing;
                SongStarted();
                if (recorderState == RecorderStates.Recording)
                {
                    recorderNextTrackTitle = "Song - " + songLoaded + " " + songLoadedTitle + " (" + songLoadedScripture + ")";
                    if (auto && (recording.Type == MeetingType.SchoolServiceMeeting || recording.Type == MeetingType.TalkWatchtowerStudy || recording.Type == MeetingType.COVisit) && songNumberPlayed == 1 && recorderCurrentDiscNumber == 1)
                    {
                        Logs.Information("Song Player", "Second song starting, splitting meeting");
                        RecorderDisc();
                    }
                    else
                    {
                        RecorderTrack();
                    }
                }
                else
                {
                    LockButtonsWithTimeOut();
                }
                try
                {
                    songPlayer.Play();
                    songPlayer.Ending += new EventHandler(SongEnded);
                    Logs.Information("Song Player", "Playing song - Song Number: " + songLoaded + " Duration: " + (int)(songPlayer.Duration / 60) + ":" + (songPlayer.Duration % 60).ToString("00"));

                }
                catch (Exception e)
                {
                    Logs.Error("Song Player", "Unable to play song. The file may be missing, corrupt or unaccessible - Error: ", e.ToString());
                    songState = SongStates.Loaded;
                }
            }
            else if (songState == SongStates.Playing)
            {
                songPlayer.Stop();
                songState = SongStates.Loaded;
                SongStopped();
                SongLoaded();
            }
        }

        void SongEnded(object sender, EventArgs e)
        {
            songState = SongStates.Loaded;
            Logs.Information("Song Player", "Song finished - Song Number: " + songLoaded);
            if (recorderState == RecorderStates.Recording)
            {
                RecorderTrack();
                songNumberPlayed++;
            }
            if (songNumberPlayed == songNumExpected) if (SongLastPlayed != null) SongLastPlayed();
            SongStopped();
            SongUnload();
        }

        public void SongUnload()
        {
            if (songState != SongStates.Playing)
            {
                songState = SongStates.Ready;
                SongUnloaded();
            }
        }

    }
}
